<template>
  <div class="container">

    <div v-for="paper in papers" :key="paper.id">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>{{  paper.title  }}</span>
          <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button>
        </div>
        <div class="text item"> 开始时间: {{ paper.startTime | dateFormat }} </div>
        <div class="text item"> 截止时间: {{ paper.endTime | dateFormat }} </div>
      </el-card>
    </div>

    <!-- 发布试卷 -->
    <el-card class="box-card">
      <div class="text item add">
        <el-button
          style="width: 100%;height: 100%"
          icon="el-icon-circle-plus-outline"
          @click="issuePaperFormDialog = true">
        </el-button>
      </div>
    </el-card>

    <!-- 发布试卷的弹窗表单 -->
    <el-dialog title="发布试卷" :visible.sync="issuePaperFormDialog" top="8vh">
      <el-form :model="issuePaperForm" size="mini" label-width="80px">
        <el-form-item label="试卷标题">
          <el-input v-model="issuePaperForm.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="开始组卷">
          <el-button type="primary" @click="handleCheckData" plain>
            目前题数 -- {{ selectQuestions['len'] }}
          </el-button>
<!--          <el-transfer-->
<!--            v-model="issuePaperForm.questions"-->
<!--            :props="{-->
<!--              key: 'id',-->
<!--              label: 'question'-->
<!--            }"-->
<!--            :data="data">-->
<!--            <span slot-scope="{ option }">-->
<!--              <el-tooltip class="item" effect="dark" :content="option.type" placement="right">-->
<!--                <span class="question_title">{{ option.question }}</span>-->
<!--              </el-tooltip>-->
<!--            </span>-->
<!--          </el-transfer>-->
        </el-form-item>
        <el-form-item label="开始时间">
          <el-col :span="11">
            <el-date-picker
              type="date"
              placeholder="选择日期"
              v-model="issuePaperForm.startTime.pre"
              style="width: 100%;"
              value-format="timestamp"></el-date-picker>
          </el-col>
          <el-col class="line" :span="2">-</el-col>
          <el-col :span="11">
            <el-time-picker
              placeholder="选择时间"
              v-model="issuePaperForm.startTime.suf"
              style="width: 100%;"></el-time-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-col :span="11">
            <el-date-picker
              type="date"
              placeholder="选择日期"
              v-model="issuePaperForm.endTime.pre"
              style="width: 100%;"
              value-format="timestamp"></el-date-picker>
          </el-col>
          <el-col class="line" :span="2">-</el-col>
          <el-col :span="11">
            <el-time-picker
              placeholder="选择时间"
              v-model="issuePaperForm.endTime.suf"
              style="width: 100%;"></el-time-picker>
          </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="issuePaper">发 布</el-button>
      </div>
    </el-dialog>

    <!-- 组卷抽屉 -->
    <el-drawer
      title="开始组卷"
      :visible.sync="questionsFormDialog"
      direction="rtl"
      :before-close="handleClose"
      size="40%"
      :close-on-press-escape="false">
      <div class="demo-drawer__content" style="padding: 0 10px;text-align: center">

        <el-select v-model="type" placeholder="请选择题型" size="small" style="margin-bottom: 30px">
          <el-option
            v-for="item in types"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>

        <el-table
          :data="tableData"
          height="300"
          border
          ref="checkTable"
          size="mini"
          @selection-change="handleSelectionChange"
          style="width: 100%">
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
            prop="question"
            label="题目">
          </el-table-column>
        </el-table>

        <div slot="footer" class="dialog-footer" style="text-align: center;margin-top: 10px">
          <el-button type="warning" @click="resetQuestions">重新组卷</el-button>
          <el-button type="primary" @click="completeQuestions">完成组卷</el-button>
        </div>
      </div>
    </el-drawer>

  </div>
</template>

<script>
import { Info, Error, Confirm, Success } from "../../utils/element.config.js";
import { GetQuestions, IssuePaper, GetPapers } from "../../api/public";

export default {
  data(){
    return{
      types: [ // 选择器的按钮数据
        {
          value: 'radio',
          label: '单选题'
        },
        {
          value: 'multi',
          label: '多选题'
        },
        {
          value: 'judge',
          label: '判断题'
        }
      ],
      type: 'radio', // 题型
      papers: [],
      tableData: [],
      questions: { // 存储所有的试题信息
        'radio': [],
        'multi': [],
        'judge': []
      },
      issuePaperFormDialog: false,
      questionsFormDialog: false,
      selectQuestions: { // 用来缓存当前选中的题目
        'radio': [],
        'multi': [],
        'judge': [],
        'len': 0 // 用来存储长度
      },
      issuePaperForm: {
        title: '',
        questions: [],
        startTime: {
          pre: '',
          suf: ''
        },
        endTime: {
          pre: '',
          suf: ''
        }
      },
      data: []
    }
  },
  created() {
    /* 获取所有的试卷 */
    GetPapers().then(result => {
      if( result.code === 200 ){
        /* 修改试卷中的时间 */
        for( let i = 0; i < result.data.length; i++ ){
          result['data'][i]['startTime'] = Date.parse(result['data'][i]['startTime']);
          result['data'][i]['endTime'] = Date.parse(result['data'][i]['endTime']);
        }
        this.papers = result.data
      }else if( result.code === 300 ){
        Error(result.message);
      }
    })
  },
  methods: {
    /** 完成组卷按钮 **/
    completeQuestions(){

      Confirm("是否完成组卷?").then(()=>{
        let changeQuestions = [];
        Object.keys(this.selectQuestions).forEach(key => {
          if( key !== 'len' ){
            this.selectQuestions[key].forEach(question => {
              changeQuestions.push(question.id);
            })
          }
        })
        this.issuePaperForm.questions = changeQuestions;
        this.questionsFormDialog = false;
      })

    },
    /** 重新组卷按钮 **/
    resetQuestions(){
      Confirm("是否重新组卷?").then(()=>{
        this.type = 'radio';
        this.selectQuestions= { // 用来缓存当前选中的题目
          'radio': [],
          'multi': [],
          'judge': [],
          'len': 0 // 用来存储长度
        }
      }).catch(()=>{
        Info("取消重新组卷");
      })

    },
    /** 回显组卷抽屉中 **/
    handleCheckData () {
      this.$nextTick(() => {
        this.selectQuestions[this.type].forEach((row) => {
          this.$refs.checkTable.toggleRowSelection(row,true);
        });
      });
      this.questionsFormDialog = true;
    },
    /** 获取组卷抽屉中选中的内容 **/
    handleSelectionChange(value){
      this.selectQuestions[this.type] = value
      this.selectQuestions['len'] =
        this.selectQuestions['radio'].length + this.selectQuestions['multi'].length + this.selectQuestions['judge'].length
    },
    /** 组卷抽屉 **/
    handleClose(done) {
      this.$confirm('确认关闭？这将会失去当前所选数据')
        .then(_ => {
          this.selectQuestions = { // 用来缓存当前选中的题目
            'radio': [],
            'multi': [],
            'judge': [],
            'len': 0 // 用来存储长度
          }
          this.type = 'radio';
          this.questionsFormDialog = false;
          done();
        })
        .catch(_ => {});
    },
    /** 获取题目列表 **/
    getQuestionsList(){
      GetQuestions().then(result => {
        if( result.code === 200 ){
          let radio = [];
          let multi = [];
          let judge = [];
          /* 对题目的数据进行处理 */
          result.data.forEach(item => {
            if( item.type === 'radio' ){
              radio.push(item);
            }else if( item.type === 'multi' ){
              multi.push(item);
            }else if( item.type === 'judge' ){
              judge.push(item);
            }
          })
          this.questions = {
            'radio': radio,
            'multi': multi,
            'judge': judge
          }
          this.tableData = this.questions['radio']
        }else if( result.code === 300 ){
          Error("请求数据获取失败， 请重试")
        }
      })
    },
    /** 发布试卷 **/
    issuePaper(){
      /* 判断日期时间是否符合 */
      if( !this.dateTimeValidation(this.issuePaperForm.startTime)
        || !this.dateTimeValidation(this.issuePaperForm.endTime) )
        return;
      /* 判断开始时间和结束时间 */
      let start = this.dataTimeConvertor(this.issuePaperForm.startTime);
      let end = this.dataTimeConvertor(this.issuePaperForm.endTime);
      if( end - start <= 0 ){
        Error("结束时间必须大于开始时间")
        return;
      }
      /* 将时间戳存到对象中 */
      this.issuePaperForm.startTime = (start);
      this.issuePaperForm.endTime = (end);
      let clone = JSON.parse(JSON.stringify(this.issuePaperForm));
      /* 这是为了存到后端 */
      this.issuePaperForm.startTime = this.$options.filters['dateFormat'](start);
      this.issuePaperForm.endTime = this.$options.filters['dateFormat'](end);
      /* 发起请求添加到数据库中 */
      Confirm("是否发布该试卷", "确认发布").then(() => {

        IssuePaper(this.issuePaperForm).then(result => {
          if( result.code === 200 ){
            /* 前端添加数据的逻辑 */
            this.issuePaperForm.id = this.papers.length + 1;
            this.papers.unshift(clone);
            Success("发布成功");
            this.issuePaperForm = {
              title: '',
              questions: [],
              startTime: {
                pre: '',
                suf: ''
              },
              endTime: {
                pre: '',
                suf: ''
              }
            }
            this.issuePaperFormDialog = false;
          }else if( result.code === 300 ){
            Error(result.message)
          }
        })

      }).catch(() => {
        Info("已取消发布");
      })
    },
    /** 取消按钮 **/
    cancel(){
      this.issuePaperForm =  {
        title: '',
        questions: [],
        startTime: {
          pre: '',
          suf: ''
        },
        endTime: {
          pre: '',
          suf: ''
        }
      }
      Info("已取消试卷发布");
      this.issuePaperFormDialog = false;
    },
    /** 日期校验器: 返回bool
     * 分析: 前缀pre 时间戳格式: 日期, 时间都是00:00:00
     *      后缀suf 标准格式: 只获取时间信息 **/
    dateTimeValidation(data){
      let pre = data.pre; // 获取时间的前缀
      let suf = data.suf; // 获取时间的后缀
      let todayDateTime = new Date();
      let todayTime = this.getMillisecondValue(todayDateTime);
      let oneDayTime = 24 * 60 * 60 * 1000;
      /* 安全判断: 获取当前时间, 然后判断选中的时间是否是当前时间之后 */
      let changeTime = this.getMillisecondValue(suf);
      if( todayDateTime.getTime() - todayTime > pre ){
        Error("日期至少选择是今天");
        return false;
      }
      /* 安全判断: 如果是今天, 那么时间必须是当前时间以后 */
      if( (pre === todayDateTime.getTime() - todayTime) && todayTime > changeTime ){
        Error("时间至少选择超过当前时间");
        return false;
      }
      return true;
    },
    /** 日期转换器: 返回时间戳
     * 分析: 前缀pre 时间戳格式: 日期, 时间都是00:00:00
     *      后缀suf 标准格式: 只获取时间信息 **/
    dataTimeConvertor(data){
      let pre = data.pre; // 获取日期的前缀
      let suf = data.suf; // 获取时间的后缀
      /*获取时间毫秒值*/
      let changeTime = this.getMillisecondValue(suf);
      return parseInt(pre) + changeTime;
    },
    /** 计算一个日期的毫秒值 **/
    getMillisecondValue(date){
      if( date instanceof Date)
        return (date.getHours() * 60 * 60 + date.getMinutes() * 60 + date.getSeconds()) * 1000 + date.getMilliseconds();
      return 0;
    }
  },
  mounted() {
    this.getQuestionsList()
  },
  computed: {},
  watch: {
    type: function(value){ // 监听 题型 的变化
      this.tableData = this.questions[value]
      // this.handleCheckData()
    }
  }
}
</script>

<style scoped>
.container{
  margin-top: 20px;
  width: 1331px;
  display: flex;
  flex-wrap: wrap;
}
.text {
  font-size: 16px;
}

.item {
  margin-bottom: 18px;
}

.add{
  height: 162px;
}

.add /deep/ i{
  font-size: 152px !important;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}
.box-card {
  margin-left: 25px;
  margin-right: 25px;
  margin-bottom: 40px;
  width: 280px;
  height: 200px;
}
.el-form-item /deep/ .el-transfer-panel{
  width: 255px;
}
.el-form-item /deep/ .el-transfer__buttons{
  padding: 0 10px;
}
.el-form-item /deep/ .el-transfer-panel__item.el-checkbox .el-checkbox__label{
  padding-left: 0;
}
.el-form-item /deep/ .el-checkbox__label button{
  padding-left: 26px;
  overflow: hidden;
}
.el-form-item /deep/ .el-transfer-panel__item{
  padding-left: 10px;
}
.question_title{
  padding-left: 22px;
  font-size: 14px;
}
</style>
